package javabasics.netty.login.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import javabasics.netty.login.protocol.PacketCodeC;

/**
 * @Author suxiaoxiao
 * @Date 2019/9/18 21:32
 * @Version 1.0
 */
public class Spliter extends LengthFieldBasedFrameDecoder {

    private static final int LENGTH_FIELD_OFFSET = 7;
    private static final int LENGTH_FIELD_LENGTH = 4;

    public Spliter() {
        // LengthFieldBasedFrameDecoder 定长拆包 防止黏包
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

        // 使用魔数来拒绝非本协议连接
        if (in.getInt(in.readerIndex()) != PacketCodeC.MAGIC_NUMBER) {
            ctx.channel().close();
            return null;
        }

        // 使用 LengthFieldBasedFrameDecoder 判断包是否完整
        return super.decode(ctx, in);
    }
}
